﻿using System.Linq;
using NHibernate;
using Web.Entities.Enums;
using Web.NetworkWorkers;

namespace Web.HelperClasses.Inflexion
{
	public class YaInflector : IInflector
	{
		private readonly ISession session;
		private readonly INetworkHelper networkHelper;
		private readonly IInflectionFactory inflectionFactory;

		public YaInflector(ISession session, INetworkHelper networkHelper, IInflectionFactory inflectionFactory)
		{
			this.session = session;
			this.networkHelper = networkHelper;
			this.inflectionFactory = inflectionFactory;
		}

		public string Inflect(string normalForm, Case c, bool singular)
		{
			var doc = networkHelper.GetXML("http://export.yandex.ru/inflect.xml?name=" + normalForm);
			if (doc == null)
				return "";
			var inflectedForm = doc.Root.Elements("inflection")
				.Where(x => x.Attribute("case").Value == ((int) c).ToString())
				.Select(x => x.Value)
				.FirstOrDefault();
			if (inflectedForm == null)
				return "";

			session.Save(inflectionFactory.Create(c, normalForm, singular, inflectedForm));
			return inflectedForm;
		}
	}
}